package vinux.web.api.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.vinux.utils.security.Security;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import vinux.service.common.base.APIResult;
import vinux.service.common.page.Pagination;
import vinux.service.common.pension.PensionUtils;
import vinux.service.common.statics.LogConstant;
import vinux.service.common.statics.SysConstant;
import vinux.service.common.util.CollectionUtils;
import vinux.service.common.util.StringUtils;
import vinux.service.core.utils.DateUtils;
import vinux.service.core.utils.LoggerUtils;
import vinux.service.core.utils.SystemLogUitls;
import vinux.service.entity.expenseacount.ExpenseAcount;
import vinux.service.entity.povertyout.ProvertyOut;
import vinux.service.entity.userbaseinfo.UserBaseInfo;
import vinux.service.entity.voteputlog.VotePutLog;
import vinux.service.service.expenseacount.service.ExpenseAcountService;
import vinux.service.service.provertyout.service.ProvertyoutService;
import vinux.service.service.userbaseinfo.service.UserBaseInfoService;
import vinux.service.service.voteputlog.service.VotePutLogService;

/**
 * 
 * 对外开放接口
 * @author chenxiwei
 *
 */

@Component
@RequestMapping("/pension/open")
public class OpenPensionController {

	@Autowired
	UserBaseInfoService userBaseInfoService;
	
	@Autowired
	ExpenseAcountService expenseacountservice;
	
	@Autowired
	ProvertyoutService provertyoutService;
	
	@Autowired
	VotePutLogService voteService;
	/**
	 * 对外开放接口通过用户ID查询用户是否为养老用户
	 * @param UserId
	 * @return result
	 *  {
	 *  	status：200成功，500有异常
	 *  	message：查询信息成功或失败
	 *  	result：是不是养老人员，如果UserId为空则result=null
	 *  }
	 */
	@RequestMapping("/isNotAged")
	@ResponseBody
	public APIResult<String> isNotAged(String userId){
		
		APIResult<String> result = new APIResult<String>();
		Exception methodMessage = null;
		String dncrypt_userId = "";
		result.setStatus(200);
		result.setMessage("查询信息成功");
		LoggerUtils.debug(getClass(), "开始查询 "+"{userId:}"+userId);
		if(StringUtils.isBlank(userId)){
			result.setStatus(500);
			result.setMessage("用户ID为空");
			result.setResult(null);
			return result;
		}
		try {
			dncrypt_userId = Security.decrypt(userId);
			UserBaseInfo userBaseInfo = userBaseInfoService.selectByUserId(Long.parseLong(dncrypt_userId));
			if(StringUtils.isNotBlank(userBaseInfo)){
				LoggerUtils.debug(getClass(), "有查询结果 "+"{UserBaseInfo:}"+userBaseInfo.toString());
				if( (userBaseInfo.getUserType()+"").equals("1")){
					result.setResult(SysConstant.PENSION_TYPE);
				}else{
					result.setResult(SysConstant.NOT_PENSION_TYPE);
				}
			}else{
				result.setResult(SysConstant.NOT_PENSION_TYPE);
			}
			
		} catch (Exception e) {
			result.setStatus(500);
			result.setMessage("查询信息失败");
			methodMessage = e;
			LoggerUtils.debug(getClass(), "厨房调用养老接口，本地查询异常");
		} finally {
			SystemLogUitls.info(null, "{dncrypt_userId:"+dncrypt_userId+",userId:"+userId+"}",
					result.toString()+"", getClass(),
					userId, methodMessage,
					LogConstant.DATA_DEAL_READ,
					LogConstant.SYSTEM_YANGLAO, "樱桃养老提供对外开放接口", SysConstant.PENSION_OPEN_ISNOTAGED,
					LogConstant.OTHER_LOG_API);
		}
		return result;
	}
	
	/**
	 * 对外开放接口补贴强
	 * @author suchao
	 * @date  2016-07-13
	 * @param pageNo
	 * @param pageSize
	 * @return result
	 */
	@RequestMapping("getSubsidyInfo")
	@ResponseBody
	public APIResult<JSONObject> getSubsidyInfo(Integer pageNo,Integer pageSize){
		Exception methodMessage = null;
		APIResult<JSONObject> result = new APIResult<>();
		result.setStatus(SysConstant.APIRESULT_STATUS_200);
		result.setMessage("查询信息成功");
		if(pageNo==null || pageSize==null){
			result.setStatus(SysConstant.APIRESULT_STATUS_500);
			result.setMessage("查询信息失败");
			return result;
		}
		Pagination<ExpenseAcount> page = new Pagination<>();
		List<ExpenseAcount> ealist = CollectionUtils.newArrayList();
		Map<String ,Object> map = new HashMap<>();
		try{
			page = expenseacountservice.findByPageBySqlId("selectAllsubsidy", map, pageNo, pageSize);
			ealist = page.getList();
			
			for(ExpenseAcount ea:ealist){

				switch(ea.getApplyType()){
				case 1:
					ea.setExpenseType("订餐");
					break;
				case 2:
					ea.setExpenseType("家政");
					break;
				case 3:
					ea.setExpenseType("旅行");
					break;
				case 4:
					ea.setExpenseType("护理");
					break;
				case 5:
					ea.setExpenseType("旅游");//线路
					break;
				case 6:
					ea.setExpenseType("调理");
					break;
				}
			}
			
			JSONArray  listarray = new JSONArray();
			for(ExpenseAcount data : ealist){
				String name = data.getNamee();
				String head_photo = data.getHeadPhoto();
				double order_money = data.getOrderMoney();
				double apply_pension_index = data.getApplyPensionIndex();
				double apply_money = data.getApplyMoney();
				String expenseType = data.getExpenseType();
				Date apply_time = data.getApplyTime();
				JSONObject expens = new JSONObject();
				expens.put("name", name);
				expens.put("head_photo", head_photo);
				expens.put("order_money", order_money);
				expens.put("apply_pension_index", apply_pension_index);
				expens.put("apply_money", apply_money);
				expens.put("expenseType", expenseType);
				String date = DateUtils.formaterDate(apply_time, "yyyy/MM/dd HH:mm");
				expens.put("apply_time", date);
				listarray.add(expens);
			}
			JSONObject list = new JSONObject();
			list.put("totalCount", page.getTotalCount());
			list.put("list", listarray);
			result.setResult(list);
		}catch(Exception e){
			methodMessage = e;
		}finally{
			SystemLogUitls.info(null, "{pageNo:+"+pageNo+",pageSize:"+pageSize+"}",
					result.toString()+"", getClass(),
					"{pageNo:+"+pageNo+",pageSize:"+pageSize+"}", methodMessage,
					LogConstant.DATA_DEAL_READ,
					LogConstant.SYSTEM_YANGLAO, "樱桃养老提供对外开放接口补贴墙", SysConstant.PENSION_OPEN_GETSUBSIDYINFO,
					LogConstant.OTHER_LOG_API);
		}
		
		return result;
	}
	
	/**
	 * 理事会投票结果回调接口
	 * @Date 2016年10月21日
	 * @return 
	 * @param
	 * @author suchao
	 */
	@RequestMapping("counciVoteCallBack")
	@ResponseBody
	public APIResult<JSONObject> CouncilVoteCallBack(String projectId,String wateNum,String customerId ,String customerLoginName,
							String groupId,Integer voteNum,Integer agreeNum,Integer disAgreeNum,String voteEndTime,String voteState){
		APIResult<JSONObject> result = new APIResult<JSONObject>();
		Exception methodMessage = null;
		result.setStatus(SysConstant.APIRESULT_STATUS_200);
		result.setMessage("查询信息成功");
		boolean updateStatus = true;
		if(wateNum==null||customerId==null){
			result.setStatus(SysConstant.APIRESULT_STATUS_500);
			result.setMessage("查询信息失败");
			return result;
		}
		String decryptCustomerId = Security.decrypt(customerId);
		String decryptGroupId = Security.decrypt(groupId);
		VotePutLog  voteLog = new VotePutLog();
		voteLog.setCustomerId(Long.valueOf(decryptCustomerId));
		voteLog.setWateNum(wateNum);
		voteLog.setCustomerLoginName(customerLoginName);
		voteLog.setGroupId(decryptGroupId);
		voteLog.setVoteNum(voteNum);
		voteLog.setAgreeNum(agreeNum);
		voteLog.setUpdateTime(new Date());
		voteLog.setDisagreeNum(disAgreeNum);
		voteLog.setVoteStatus(Integer.valueOf(voteState));
		voteLog.setVoteEndTime(PensionUtils.formatString2Date(voteEndTime, "yyyy-MM-dd HH:mm:ss"));
		try{
			updateStatus = voteService.updateApplyUserStatus(voteLog);
			if(updateStatus){
				LoggerUtils.debug(getClass(), "投票结果更新成功");
				result.setStatus(SysConstant.APIRESULT_STATUS_200);
				result.setMessage("回调成功");
			}else{
				result.setStatus(SysConstant.APIRESULT_STATUS_500);
				result.setMessage("回调失败");
			}
		}catch(Exception e){
			result.setStatus(SysConstant.APIRESULT_STATUS_500);
			result.setMessage("回调失败"+e.getMessage());
			methodMessage = e;
		}finally{
			SystemLogUitls.info(null, null,
					result.toString(), getClass(),
					voteLog.toString()+"", methodMessage,
					LogConstant.DATA_DEAL_READ,
					LogConstant.SYSTEM_YANGLAO, "理事会投票回调结果", SysConstant.PENSION_OPEN_COUNCILVOTECALLBACK,
					LogConstant.OTHER_LOG_API);
		}
//		System.out.println("result=================="+result.toString());
		return result;
	}
	
	/**
	 * 
	 * @Title: fupinbaoxiaoCallBack   
	 * @Description: TODO(3.1 注资接口–养老扶贫报销回调接口（供基金系统使用）)
	 * http://manager.vinuxagedcare.com/pension/open/fupinbaoxiaoCallBack.vhtml?requestSn=1001&type=2
	 * @param: @param requestSn
	 * @param: @param type
	 * @param: @return      
	 * @return: APIResult<JSONObject>      
	 * @throws
	 */
	@RequestMapping("fupinbaoxiaoCallBack")
	@ResponseBody
	public APIResult<JSONObject> fupinbaoxiaoCallBack(String requestSn,String type){
		Exception methodMessage = null;
		APIResult<JSONObject> result = new APIResult<>();
		result.setStatus(SysConstant.APIRESULT_STATUS_200);
		result.setMessage("更新信息成功");
		
		if(requestSn==null || type==null || requestSn=="" || type==""){
			result.setStatus(SysConstant.APIRESULT_STATUS_500);
			result.setMessage("输入参数不全");
			return result;
		} 
		int returnCount = 0;
		try{
			Map<String,Object> findMap = new LinkedHashMap<String, Object>();
			findMap.put("requestsn", requestSn);
			ProvertyOut provertyOutResult = provertyoutService.findOne(findMap);
			if(provertyOutResult==null){
				result.setStatus(SysConstant.APIRESULT_STATUS_500);
				result.setMessage("requestsn="+requestSn+"不存在!");
				return result;
			}
			provertyOutResult.setType(type);
			provertyOutResult.setUpdateTime(new Date());
			returnCount = provertyoutService.updateByPrimaryKeySelective(provertyOutResult);
			if(returnCount<=0){
				result.setStatus(SysConstant.APIRESULT_STATUS_500);
				result.setMessage("更新失败returnCount="+returnCount+"!");
				return result;
			}
			JSONObject object = new JSONObject();
			result.setResult(object);
		}catch(Exception e){
			methodMessage = e;
		}finally{
			SystemLogUitls.info(null, "{requestSn:+"+requestSn+",type:"+type+"}",
					result.toString()+"", getClass(),
					"{requestSn:+"+requestSn+",type:"+type+"}", methodMessage,
					LogConstant.DATA_DEAL_READ,
					LogConstant.SYSTEM_YANGLAO, "养老扶贫报销回调接口", SysConstant.PENSION_OPEN_FUPINBAOXIAOCALLBACK,
					LogConstant.OTHER_LOG_API);
		}
		
		return result;
	}
	
	public static void main(String[] args) {
//		customerId o3YoS4FRk5Y=
		
//		String sec = Security.encrypt("201334");
//		System.out.println(sec);
		
		String txt = Security.decrypt("o3YoS4FRk5Y=");
		System.out.println(txt);
		
		
	}
	
}




